<?php
namespace yphp;

/**
 * Class Controller
 * @package yphp
 * 基类控制器
 */
class Controller extends Instance
{
    // 构造方法
    function construct()
    {
        return self::single();
    }

    // 加载控制器
    final static function load($path)
    {
        $class = 'app\controller\\'.str_replace('/','\\',$path);
        return $class::instance();
    }

    // 视图加载
    final static function view($path,$assign = null,$cache = null)
    {
        return View::instance($path)->html($assign,$cache);
    }

    // 验证令牌
    final static function check_token()
    {
        $csrf_token = Session::get('csrf_token');
        if (!is_null($csrf_token)){
            if($csrf_token === Request::instance()->param('csrf_token')){
                return true;
            } else {
                return false;
            }
        } else {
            throw new \Exception('未填写CSRF令牌，无法验证');
        }
    }

    // 成功提示页面
    final static function layerShow($msg=null,$url=null,$time=3000)
    {
        if(is_null($url)){
            echo "<script src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script><script src='http://www.yuqingyong.cn/static/home/js/layer.js'></script><script>layer.msg('".$msg."');setTimeout('history.back(-1)',".$time.");</script>";
        } else {
            echo "<script>window.location.href='".$url."';</script>";
        }
        
    }

    // 验证码验证,不区分大小写
    final static function checkCode($code)
    {
        $session_code = \yphp\Session::get('code');
        if(empty($code)){
            $this->layerShow('未填写验证码');
        } else {
            # 转为小写
            if(strtolower($session_code) === strtolower($code)){
                return true;
            } else {
                return false;
            }
        }
    }

}